import cache from '@/utils/token.js'
import path from '@/utils/path.js'
import install from '@/utils/func.js'
var websock = null;
var hasUid = null;
var webSocketState = true;
var webStatue = false;
const openWebSocket = (uid) => {
	hasUid = uid;
	websock = null;
	websock = uni.connectSocket({
		header: {
			'Authorization': 'Bearer ' + cache.getCache('youthToken'),
			'content-type': 'application/json',
		},
		url: path.socketUrl + '?user_id=' + uid + '&room_id=0&object_id=0',
		method: 'GET',
		success() {
			console.log('全局websocket已开启');
			webSocketState = true;
		}
	});
	websock.onOpen(webSocketOnopen)
	websock.onMessage(webSonMessage)
	websock.onClose(webSonClose)
	websock.onError(webSonError)
}

const webSocketOnopen = () => { // 连接建立之后执行send方法发送数据，连接成功
	const data = {
		token: cache.getCache('youthToken')
	};
	if (data.token) {
		// const result = JSON.stringify(data);
		websock.send({
			data: 'ping'
		})

		uni.$func.request('/chat/read').then(res => {
			console.log('webSocketOnopen执行的read')
			if (res.data.no_read == 1) {

				// 导航角标
				uni.showTabBarRedDot({
					index: 2,
				})
				webStatue = true;
				uni.$emit('webStatueType', webStatue);
			} else {
				uni.hideTabBarRedDot({
					index: 2,
				})
				webStatue = false;
			}
		})

	} else {
		websock.close()
	}
}
const webSonMessage = (e) => { // 数据接收
	let message = JSON.parse(e.data);
	console.log('webSonMessage执行的read')
	uni.$func.request('/chat/read').then(res => {
		if (res.data.no_read == 1) {
			// 导航角标
			uni.showTabBarRedDot({
				index: 2,
			})

			webStatue = true;
			uni.$emit('webStatueType', webStatue);
		} else {
			uni.hideTabBarRedDot({
				index: 2,
			})

			webStatue = false;
		}
	})
}
//发送消息
const sendmessage = (e) => {
	console.log(e, '全局webSocket提交的数据')
	// let message = JSON.parse(e);
	// this.websock.send({
	// 	data: message.type + '+++' + message.message
	// })
}
const webSonClose = (e) => {
	console.log('全局webSocket触发了close',webSocketState,'webSocketState的状态')
	// websock.close();
	if (webSocketState) { // 非手动关闭自动从连
		webSocketReconnect()
	}
}
const webSonError = () => {
	// console.log('全局webSocket触发了onerror',webSocketState,'webSocketState的状态')
	// websock.close()
	// if (webSocketState) { // 非手动关闭自动从连
	// 	console.log('全局webSocket触发了断开了重连');
	// 	webSocketReconnect()
	// }
}
const webSocketReconnect = () => {
	console.log('执行了重启webSocketReconnect')
	openWebSocket(hasUid);
}


const webSocketClose = () => {
	console.log('全局webSocket已关闭,这里触发了')
	webSocketState = false;
	websock.close();
}

export default {
	openWebSocket,
	webSocketState,
	webSocketClose,
	webStatue

}